//
//  DSSearchViewController.m
//  DS爱信
//
//  Created by 秦建英 on 14-5-27.
//  Copyright (c) 2014年 秦建英. All rights reserved.
//

#import "DSSearchViewController.h"
#import "DSLgViewController.h"
#import "Header.h"
#import "DingSh.h"
#import "FMDBManager.h"
@interface DSSearchViewController ()
@end
@implementation DSSearchViewController
{
    ABAddressBookRef addressBook;
    NSMutableArray *addressBookTemp;
    NSString *_nameString;
    DingSh * _addressBook;
    UIImageView *_imageview3;
    NSTimer *_tite;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        addressBookTemp =[[NSMutableArray alloc]init];
        _dataArray =[[NSMutableArray alloc]init];
}
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self gcd];
}
- (void)gcd{
    dispatch_queue_t t = dispatch_queue_create(NULL, NULL);
    dispatch_async(t, ^{
        [self readAllPeoples];
    });
    dispatch_async(dispatch_get_main_queue(), ^{
        [self initGuide];
    });
}
- (void)initGuide
{
    _imageview3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, DeviceHeight)];
    [_imageview3 setImage:[UIImage imageNamed:@"sc.jpg"]];
    [self.view addSubview:_imageview3];
    
   _tite= [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer) userInfo:nil repeats:YES];
}
-(void)timer
{
    [self presentViewController:[[DSLgViewController alloc] init] animated:YES completion:^{
    }]; 
    [_imageview3 removeFromSuperview];
    [_tite invalidate];
}
-(void)readAllPeoples
{
    ABAddressBookRef addressBooks = nil;
    
    if ([[ UIDevice currentDevice ]. systemVersion floatValue ]>= 6.0 ) {
        addressBooks = ABAddressBookCreateWithOptions ( NULL , NULL );
        dispatch_semaphore_t sema = dispatch_semaphore_create ( 0 );
        
        ABAddressBookRequestAccessWithCompletion (addressBooks, ^( bool granted, CFErrorRef error){ dispatch_semaphore_signal (sema);});
        dispatch_semaphore_wait (sema, DISPATCH_TIME_FOREVER );
    }else
    {
        addressBooks = ABAddressBookCreate ();
    }
    // 获取通讯录中的所有人
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople (addressBooks);
    // 通讯录中人数
    CFIndex nPeople = ABAddressBookGetPersonCount (addressBooks);
    
    for ( NSInteger i = 0 ; i<nPeople; i++)
    {
        _addressBook = [[ DingSh alloc ] init ];
        // 获取个人
        ABRecordRef person = CFArrayGetValueAtIndex (allPeople, i);
        CFTypeRef abName = ABRecordCopyValue (person, kABPersonAddressProperty );
        
        CFTypeRef abLastName = ABRecordCopyValue (person, kABPersonLastNameProperty );
        
        CFStringRef abFullName = ABRecordCopyCompositeName (person);
        
        _nameString = ( __bridge NSString *)abName;
        
        NSString *lastNameString = ( __bridge NSString *)abLastName;
        
        if (( __bridge id )abFullName != nil ) {
            
            _nameString = ( __bridge NSString *)abFullName;
            
        } else {
            if (( __bridge id )abLastName != nil )
            {
                _nameString = [ NSString stringWithFormat : @"%@ %@" , _nameString, lastNameString];
            }
        }
        _addressBook. name = _nameString;
        _addressBook. recordID = ( int ) ABRecordGetRecordID (person);;
        
        ABPropertyID multiProperties[] = {
            
            kABPersonPhoneProperty ,
            
            kABPersonEmailProperty
            
        };
        NSInteger multiPropertiesTotal = sizeof (multiProperties) / sizeof ( ABPropertyID );
        for ( NSInteger j = 0 ; j < multiPropertiesTotal; j++) {
            ABPropertyID property = multiProperties[j];
            
            ABMultiValueRef valuesRef = ABRecordCopyValue (person, property);
            
            NSInteger valuesCount = 0 ;
            
            if (valuesRef != nil ) valuesCount = ABMultiValueGetCount (valuesRef);
            
            if (valuesCount == 0 ) {
                
                CFRelease (valuesRef);
                
                continue ;
            }
            // 获取电话号码和 email
            for ( NSInteger k = 0 ; k < valuesCount; k++) {
                CFTypeRef value = ABMultiValueCopyValueAtIndex (valuesRef, k);
                switch (j) {
                    case 0 : {
                        _addressBook. tel = ( __bridge NSString *)value;
                        
                        break ;
                    }
                }
                CFRelease (value);
            }
            CFRelease (valuesRef);
        }
        FMDBManager* manager = [FMDBManager sharedManager];
        [manager addUser:_addressBook];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end
